package com.ruoyi.system.controller;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.config.MinioUtils;
import com.ruoyi.system.domain.Blog;
import com.ruoyi.system.service.IBlogService;
import com.ruoyi.system.service.impl.BlogServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/**
 * blogController
 * 
 * @author mz
 * @date 2024-07-23
 */
@RestController
@RequestMapping("/blog")
public class ClientBlogController extends BaseController
{


    @Autowired
    IBlogService blogService;
    @Autowired
    MinioUtils minioUtils;

    @Value("${minio.bucketName}")
    String bucketName;

    @PostMapping("upload")
    public AjaxResult upload(MultipartFile file) throws Exception {
        try
        {
            String avatar = UUID.randomUUID().toString();
            minioUtils.upload(file, avatar);
            avatar = bucketName + "/" + avatar;


            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", avatar);
            ajax.put("fileName", avatar);
            ajax.put("newFileName", FileUtils.getName(avatar));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }

    }



    @PostMapping("/addBlog")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult addBlog(@RequestBody Blog blog) {

        int r = blogService.insertBlog(blog);
        if (r != 1) {
            throw new ServiceException("请联系管理员");
        }
        return AjaxResult.success("成功！");
    }
}
